package com.yuyenews.utils;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.util.List;
import java.util.Properties;

import com.alibaba.fastjson.JSONObject;
import com.yuyenews.core.util.ConfigUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 邮件工具类
 */
public class MailUtil {

    private static Logger logger = LoggerFactory.getLogger(MailUtil.class);// 日志

    /**
     * 连接协议
     */
    private static String protocol = "smtp";
    /**
     * 主机名
     */
    private static String host;
    /**
     * 端口号
     */
    private static String port;
    /**
     * 设置是否使用ssl安全连接 ---一般都使用
     */
    private static String smtpSslEnable;
    /**
     * 设置是否显示debug信息 true 会在控制台显示相关信息
     */
    private static String debug;
    /**
     * 发件箱
     */
    private static String sendMail;
    /**
     * 发件箱密码
     * 邮箱开通的stmp服务后得到的客户端授权码
     */
    private static String sendMailPwd;

    private static String auth;

    static {
        /* 读取配置文件，并给属性赋值 */
        try {
            JSONObject jsonObject = ConfigUtil.getConfig();
            JSONObject mail = jsonObject.getJSONObject("mail");

            host = mail.getString("host");
            port = mail.getString("port");
            smtpSslEnable = mail.getString("smtpSslEnable");
            debug = mail.getString("debug");
            sendMail = mail.getString("sendMail");
            sendMailPwd = mail.getString("sendMailPwd");
            auth = mail.getString("auth");
        } catch (Exception e) {
            logger.error("加载邮件配置出错",e);
        }
    }

    /**
     * 发送不带附件的邮件
     * @param title 标题
     * @param content 内容
     * @param internetAddress 收件箱
     */
    public static void sendMail(String title, String content, List<String> internetAddress){
        sendMail(title,content,internetAddress,null);
    }

    /**
     * 发送带附件的邮件
     * @param title 标题
     * @param content 内容
     * @param internetAddress 收件箱
     * @param file 附件
     */
    public static void sendMail(String title, String content, List<String> internetAddress,File[] file){

        Transport transport = null;
        try{
            Properties properties = new Properties();
            properties.put("mail.transport.protocol", protocol);// 连接协议
            properties.put("mail.smtp.host", host);// 主机名
            properties.put("mail.smtp.port", port);// 端口号
            properties.put("mail.smtp.auth", auth);
            properties.put("mail.smtp.ssl.enable", smtpSslEnable);// 设置是否使用ssl安全连接 ---一般都使用
            properties.put("mail.debug", debug);// 设置是否显示debug信息 true 会在控制台显示相关信息
            // 得到回话对象
            Session session = Session.getInstance(properties);
            // 获取邮件对象
            Message message = new MimeMessage(session);
            // 设置发件人邮箱地址
            message.setFrom(new InternetAddress(sendMail));
            // 设置收件人邮箱地址
            message.setRecipients(Message.RecipientType.TO, getInternetAddress(internetAddress));
            // 设置邮件标题
            message.setSubject(title);

            // 创建多重消息
            Multipart multipart = new MimeMultipart();

            // 设置邮件内容
            MimeBodyPart mbpContent = new MimeBodyPart();
            //mbpContent.setText(content);
            mbpContent.setContent(content,"text/html;charset=utf-8");

            multipart.addBodyPart(mbpContent);

            // 添加附件
            if(file != null){
                if(null!=file && file.length > 0){
                    for(int i=0;i < file.length;i++){
                        BodyPart attchmentPart = new MimeBodyPart();
                        // 设置要发送附件的文件路径
                        DataSource source = new FileDataSource(file[i]);
                        attchmentPart.setDataHandler(new DataHandler(source));
                        // 处理附件名称中文（附带文件路径）乱码问题
                        attchmentPart.setFileName(MimeUtility.encodeText(file[i].getName()));
                        multipart.addBodyPart(attchmentPart);
                    }
                }
            }

            // 发送完整消息
            message.setContent(multipart);

            // 得到邮差对象
            transport = session.getTransport();
            // 连接自己的邮箱账户
            transport.connect(sendMail, sendMailPwd);
            // 发送邮件
            transport.sendMessage(message, message.getAllRecipients());
        } catch (Exception e) {
            logger.error("发送邮件报错", e);
        } finally {
            try{
                if(transport != null){
                    transport.close();
                }
            } catch (Exception e) {
            }
        }


    }


    /**
     * 获取收件方邮箱对象
     * @param internetAddress 收件箱
     * @return 数组
     */
    private static InternetAddress[] getInternetAddress(List<String> internetAddress){
        try{
            InternetAddress[] internetAddressList = new InternetAddress[internetAddress.size()];

            for(int i = 0;i<internetAddress.size();i++){
                internetAddressList[i] = new InternetAddress(internetAddress.get(i));
            }

            return internetAddressList;
        } catch (Exception e){
            logger.error("获取收件方邮箱对象报错", e);
            return null;
        }

    }
}
